package com.fduss.artStore.dao.impl;

import com.fduss.artStore.dao.ArtworkGenreDao;
import com.fduss.artStore.entity.ArtworkGenre;
import com.fduss.artStore.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by alex on 27/06/2017.
 */
public class ArtworkGenreDaoImpl implements ArtworkGenreDao {
    private JdbcUtil util;

    public ArtworkGenreDaoImpl(){
        util = new JdbcUtil();
    }

    @Override
    public ArtworkGenre add(ArtworkGenre artworkGenre) {
        Connection conn = util.getConnection();
        String sql = "INSERT INTO `art`.`artworkgenres` " +
                "(`ArtWorkGenreID`, `ArtWorkID`, `GenreID`) VALUES (?, ?, ?)";

        PreparedStatement pst = null;
        boolean flag = false;

        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, artworkGenre.getArtWorkGenreId());
            pst.setInt(2, artworkGenre.getArtWorkId());
            pst.setInt(3, artworkGenre.getGenreId());
            pst.executeUpdate();
            flag = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }

        return flag ? artworkGenre: null;
    }

    @Override
    public void deleteByArtWork(int artworkId) {
        Connection conn = util.getConnection();
        String sql = "DELETE FROM `art`.`artworkgenres` WHERE `ArtWorkID`=? ";
        PreparedStatement pst = null;

        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, artworkId);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }
    }

    @Override
    public void deleteByGenre(int genreID) {
        Connection conn = util.getConnection();
        String sql = "DELETE FROM `art`.`artworkgenres` WHERE `GenreID`=? ";
        PreparedStatement pst = null;

        try{
            pst = conn.prepareStatement(sql);
            pst.setInt(1, genreID);
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            util.close(null, pst, conn);
        }
    }


}
